package com.antd.admin.server.controller;


import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import com.antd.admin.api.dto.ResetPasswdDto;
import com.antd.admin.api.dto.UserDTO;
import com.antd.admin.api.entity.SysUser;
import com.antd.admin.server.service.ISysUserService;
import com.antd.admin.server.strategy.passwd.ResetPasswdContext;
import com.antd.common.auth.security.AntdUserDetails;
import com.antd.common.auth.util.AntdSecurityUtil;
import com.antd.common.core.constant.Constant;
import com.antd.common.core.util.R;
import com.antd.common.core.vo.PageVo;
import com.antd.common.log.annotation.SystemLog;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author 子丶沫
 * @since 2020-11-18
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
public class SysUserController {

    @Autowired
    private ISysUserService userService;
    @Autowired
    private ResetPasswdContext resetPasswdContext;
    @GetMapping("/findByUsername/{username}")
    @ApiOperation("通过用户名查询用户信息")
    public R<SysUser> findByUsername(@PathVariable String username){
        return R.ok(userService.findByUsername(username));
    }

    @GetMapping("/findByMobile/{mobile}")
    @ApiOperation("通过手机号码查询用户信息")
    public R<SysUser> findByMobile(@PathVariable String mobile){
        return R.ok(userService.findByUsername(mobile));
    }
    @GetMapping("/info")
    @SystemLog(description = "获取用户信息")
    public R<Object> index(){
        AntdUserDetails user = AntdSecurityUtil.getUser();
        return R.ok(userService.findByUsername(user.getUsername()));
    }
    @GetMapping
    @SystemLog(description = "查询用户列表")
    @ApiOperation("查询用户列表")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public R<Object> list(PageVo page, UserDTO userDTO){
        return R.ok(userService.queryUserList(new Page<>(page.getPageNum(),page.getPageSize()),userDTO));
    }
    @PostMapping
    @SystemLog(description = "保存用户")
    @ApiOperation("保存用户")
    @PreAuthorize("hasAuthority('sys:user:save')")
    public R<Object> saveUser(@RequestBody UserDTO userDTO){
        return R.ok(userService.saveUser(userDTO));
    }
    @PutMapping
    @SystemLog(description = "修改用户")
    @ApiOperation("修改用户")
    @PreAuthorize("hasAuthority('sys:user:update')")
    public R<Object> updateUser(@RequestBody UserDTO userDTO){
        return R.ok(userService.updateUser(userDTO));
    }

    @DeleteMapping("/deleteUser")
    @SystemLog(description = "批量删除用户")
    @ApiOperation("批量删除用户")
    @PreAuthorize("hasAuthority('sys:user:delete')")
    public R<Object> deleteUser(String ids){
        List<String> idList = Arrays.stream(ids.split(",")).collect(Collectors.toList());
        return R.ok(userService.deleteUser(idList));
    }
    @GetMapping("/checkUniqueness")
    @ApiOperation("唯一性校验")
    public R<Object> checkUniqueness(String value,String oldValue){
        return R.ok(userService.checkUniqueness(value,oldValue));
    }

    @PostMapping("/enable/{userId}")
    @ApiOperation("启用用户")
    public R<Object> enable(@PathVariable String userId){
        return R.ok(userService.update(Wrappers.<SysUser>lambdaUpdate().set(SysUser::getLockFlag, Constant.USER_STATUS_NORMAL).eq(SysUser::getUserId,userId)));
    }

    @PostMapping("/disable/{userId}")
    @ApiOperation("禁用用户")
    public R<Object> disable(@PathVariable String userId){
        return R.ok(userService.update(Wrappers.<SysUser>lambdaUpdate().set(SysUser::getLockFlag, Constant.USER_STATUS_LOCK).eq(SysUser::getUserId,userId)));
    }

    @ApiOperation("注册")
    @PostMapping("/register")
    public R<Object> register(@RequestBody UserDTO user, HttpServletRequest request){
        String t = request.getParameter("t");
        String code = request.getParameter("imgCode");
        return R.ok(userService.register(user,t,code));
    }
    @ApiOperation("校验用户是否存在")
    @PostMapping("/checkUserExists")
    public R<Object> checkUserExists(String value){
        return R.ok(userService.count(Wrappers
                .<SysUser>query()
                .lambda()
                .eq(SysUser::getEmail,value)
                .or()
                .eq(SysUser::getPhone,value))>0);
    }
    @ApiOperation("校验用户原密码")
    @PostMapping("checkPassword")
    public R<Object> checkPassword(String password){
        AntdUserDetails userDetails = AntdSecurityUtil.getUser();
        SysUser user=userService.getById(userDetails.getUserId());
        String oldPassword = Base64.decodeStr(password, CharsetUtil.CHARSET_UTF_8);
        boolean validatePass = AntdSecurityUtil.validatePass(oldPassword, user.getPassword());
        return R.ok(validatePass);
    }

    @ApiOperation("修改用户密码")
    @PostMapping("updatePasswd")
    public R<Object> updatePasswd(String password){
        AntdUserDetails userDetails = AntdSecurityUtil.getUser();
        SysUser user=userService.getById(userDetails.getUserId());
        String newPassword = Base64.decodeStr(password, CharsetUtil.CHARSET_UTF_8);
        user.setPassword(AntdSecurityUtil.encodePassword(newPassword));
        return R.ok(userService.updateById(user));
    }

    @ApiOperation("重置密码")
    @PostMapping("/resetPasswd")
    public R<Object> resetPasswd(@RequestBody ResetPasswdDto dto){
        return R.ok(resetPasswdContext.handleResetPasswd(dto));
    }
}
